package com.ruoyi.web.controller.cpsp;
/*
    @author neu.xiangwenjuan
    @create 2022/3/28
*/

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.cpsp.mapper.DepartmentMapper;
import com.ruoyi.cpsp.mapper.TeamGroupMapper;
import com.ruoyi.cpsp.domain.*;
import com.ruoyi.cpsp.service.*;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/cpsp/evaluateRecord")
public class EvaluateRecordController {

    @Autowired
    private EvaluateRecordService evaluateRecordService;

    @Autowired
    private PerformanceHistoryService performanceHistoryService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private RegulationDetailService regulationDetailService;

    @Autowired
    private EvaluateRecordToEmployeeService evaluateRecordToEmployeeService;

    private EmployeeController employeeController = new EmployeeController();

    @ApiOperation("获得违章记录")
    @RequestMapping(value = "/getEvaluateRecord", method = RequestMethod.GET)
    @ResponseBody
    private AjaxResult getEvaluateRecordInfo(@RequestParam(defaultValue = "1") Integer pageNum,
                                         @RequestParam(defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();

        List<String> idCardList = employeeService.selectCardByDepart(departmentId, 0);
        PageHelper.startPage(pageNum,pageSize);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int session = employeeController.getSeason(new Date());

        List<EvaluateRecord> list = new ArrayList<>();

        if (role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            list = evaluateRecordService.selectEvaluateRecords(year, session);
        }else if (role.equals("department")) {
            list = evaluateRecordService.selectEvaluateRecordsByDepart(idCardList,year,session);
        }

        PageInfo pageInfo = PageInfo.of(list);
        //System.out.println(+pageInfo);
        return AjaxResult.success(pageInfo);
    }

    @ApiOperation("获取修改前违章记录")
    @RequestMapping(value = "/getUpdateEvaluateRecord", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult getInfoBeforeUpdate(Integer evaluateRecordId) {
        // 得到关联人员的信息
        List<EvaluateRecordRelated> list = evaluateRecordToEmployeeService.selectRelatedEmployees(evaluateRecordId);
        return AjaxResult.success(list);
    }

    @ApiOperation("删除关联人员")
    @RequestMapping(value = "/deleteRelatedEmployee", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult deleteRelatedEmployee(Integer id) {
        int count = evaluateRecordToEmployeeService.deleteRelatedEmployee(id);
        if (count > 0) {
            return AjaxResult.success("数据删除成功！");
        }else {
            return AjaxResult.error("数据删除失败！");
        }
    }

    /**
     * 只能修改比例
     * @param id
     * @param proportionOfPunishment
     * @return
     */
    @ApiOperation("修改关联人员扣减比例")
    @RequestMapping(value = "/updateEvaluateRecordProp", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult updateEvaluateRecord( Integer id, Double proportionOfPunishment) {
        int count = evaluateRecordToEmployeeService.updateByPrimaryId(id, proportionOfPunishment);
        if (count > 0){
            return AjaxResult.success("数据修改成功！");
        }else {
            return AjaxResult.error("数据修改失败！");
        }
    }

    @ApiOperation("导出季度汇总记录")
    @RequestMapping(value = "/loadEvaluateRecord", method = RequestMethod.POST)
    @ResponseBody
    private AjaxResult loadEvaluateRecord() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        String role = sysUser.getRoles().get(0).getRoleKey();
        SysDept dept = iSysDeptService.selectDeptById(sysUser.getDeptId());
        String departmentId = dept.getDepartmentId();
        List<EvaluateRecordDepart> ajaxResult = new ArrayList<>();
        // 所有部门的信息
        List<Department> departments = departmentService.selectAll();
        if (role.equals("department")) {// 部门领导，本部门的，按照班组筛选。
            Department department = departmentMapper.selectByDepartmentId(departmentId);
            /*EvaluateRecordDepart depart = getInfoByDepart(departmentId,department.getDepartmentName());
            ajaxResult.add(depart);*/
        }else if(role.equals("admin") || role.equals("leader") || role.equals("supervision") || role.equals("sysadmin")) {
            EvaluateRecordDepart depart = new EvaluateRecordDepart();
            for (Department department:departments) {
                /*depart = getInfoByDepart(department.getDepartmentId(),department.getDepartmentName());
                ajaxResult.add(depart);*/
            }
        }
        return AjaxResult.success(ajaxResult);
    }

    // 工具方法
    /**
     * 输入一个departmentId 返回一个map。
     */
    /*
    private EvaluateRecordDepart getInfoByDepart (String departmentId, String departmentName) {
        List<EvaluateRecordVO> list = new ArrayList<>();

        // 得到当前年份和季度。
        Calendar calendar = Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int quarter = employeeController.getSeason(new Date());
        // 得到在当前季度每个员工因为违规所扣除的绩效比例的最大值。
        List<EvaluateRecordCurrentQuarter> maxProp = evaluateRecordService.getMaxProp(year,quarter);

        DecimalFormat decFormat = new DecimalFormat("#%");

        List<String> idCardList = employeeService.selectCardByDepart(departmentId);
        // 根据employee的部门查找相应信息。
        // 得到员工数据
        List<EmployeeEntity> employees = employeeService.selectEmployeesByDepartment(departmentId);
        // 当前季度初始绩效
        List<PerformanceHistory> currentPerformance = performanceHistoryService.selectPerformanceValue(year, quarter);
        Integer product = 0;
        for (EmployeeEntity employeeEntity:employees) {
            EvaluateRecordVO evaluateRecordVO = new EvaluateRecordVO();
            evaluateRecordVO.setEmployeeName(employeeEntity.getName());
            evaluateRecordVO.setEmployeeIdCard(employeeEntity.getIdCard());
            evaluateRecordVO.setIs45Days(employeeEntity.getIs45Days());
            if (employeeEntity.getIsDirectProducer() != null) {
                if (employeeEntity.getIsDirectProducer() == 1) {
                    product = 1;
                    evaluateRecordVO.setIsDirectProducer("生产岗");
                    evaluateRecordVO.setIncreaseMoney(100);
                }else if (employeeEntity.getIsDirectProducer() == 2) {
                    product = 2;
                    evaluateRecordVO.setIsDirectProducer("辅助岗");
                    evaluateRecordVO.setIncreaseMoney(50);
                }else {
                    product = 3;
                    evaluateRecordVO.setIsDirectProducer("其他岗位");
                    evaluateRecordVO.setIncreaseMoney(0);
                }
            }else {
                evaluateRecordVO.setIncreaseMoney(0);
            }

            evaluateRecordVO.setPositionType(employeeEntity.getPositionType());
            if (employeeEntity.getTeamGroup() != null) {
                evaluateRecordVO.setTeamGroup(employeeEntity.getTeamGroup().getTeamGroupName());
            }
            for (PerformanceHistory performance:currentPerformance) {
                if (performance.getEmployeeIdCard().equals(employeeEntity.getIdCard())) {
                    evaluateRecordVO.setLastMoney(performance.getPerformanceValue());
                }
            }
            boolean flag = false;
            for (EvaluateRecordCurrentQuarter record : maxProp) {
                if (employeeEntity.getIdCard().equals(record.getEmployeeIdCard())) {
                    flag = true;
                    evaluateRecordVO.setEvaCount(record.getEmployeeCount());
                    evaluateRecordVO.setEvaName("");
                    evaluateRecordVO.setIncreaseMoney(0);
                    if (record.getMaxProp() >= 1) {
                        evaluateRecordVO.setProp(decFormat.format(100));
                        evaluateRecordVO.setPropMoney(evaluateRecordVO.getLastMoney());
                        evaluateRecordVO.setNextMoney(0);
                    } else {
                        evaluateRecordVO.setProp(decFormat.format(record.getMaxProp()));
                        evaluateRecordVO.setPropMoney(evaluateRecordVO.getLastMoney() * record.getMaxProp());
                        evaluateRecordVO.setNextMoney(evaluateRecordVO.getLastMoney() - evaluateRecordVO.getPropMoney());
                    }
                    evaluateRecordVO.setMonthMoney(evaluateRecordVO.getNextMoney());
                    evaluateRecordVO.setSumMoney(evaluateRecordVO.getNextMoney() * 3);
                    break;
                }
            }
            if (!flag) {
                evaluateRecordVO.setProp(decFormat.format(0));
                evaluateRecordVO.setPropMoney(0);
                if (product == 1) {
                    if ((evaluateRecordVO.getLastMoney() + evaluateRecordVO.getIncreaseMoney()) > 1000.0) {
                        evaluateRecordVO.setNextMoney(1000.0);
                    }else {
                        evaluateRecordVO.setNextMoney(evaluateRecordVO.getLastMoney() + evaluateRecordVO.getIncreaseMoney());
                    }
                }else {
                    if ((evaluateRecordVO.getLastMoney() + evaluateRecordVO.getIncreaseMoney()) > 500.0) {
                        evaluateRecordVO.setNextMoney(500.0);
                    }else {
                        evaluateRecordVO.setNextMoney(evaluateRecordVO.getLastMoney() + evaluateRecordVO.getIncreaseMoney());
                    }
                }
                evaluateRecordVO.setMonthMoney(evaluateRecordVO.getNextMoney());
                evaluateRecordVO.setSumMoney(evaluateRecordVO.getMonthMoney() * 3);
            }
            list.add(evaluateRecordVO);
        }
        EvaluateRecordVO total = new EvaluateRecordVO();
        for (EvaluateRecordVO recordVO : list) {
            total.setLastMoney(total.getLastMoney() + recordVO.getLastMoney());
            if (total.getIncreaseMoney() == null) {
                total.setIncreaseMoney(recordVO.getIncreaseMoney());
            }else {
                total.setIncreaseMoney(total.getIncreaseMoney() + recordVO.getIncreaseMoney());
            }
            total.setNextMoney(total.getNextMoney() + recordVO.getNextMoney());
            total.setMonthMoney(total.getMonthMoney() + recordVO.getMonthMoney());
            total.setSumMoney(total.getSumMoney() + recordVO.getSumMoney());
        }
        // 得到了list存储着整个部门的信息
        EvaluateRecordTeam evaluateRecordTeam = new EvaluateRecordTeam();
        evaluateRecordTeam.setTeamGroupName("总表");
        evaluateRecordTeam.setDataList(list);
        evaluateRecordTeam.setTotal(total);
        ArrayList<EvaluateRecordTeam> teamList = new ArrayList<>();
        teamList.add(evaluateRecordTeam);

        List<TeamGroup> teamGroupList = teamGroupMapper.findTeamGroupByDepart(departmentId);
        for (TeamGroup teamGroup : teamGroupList) {
            EvaluateRecordVO subTotal = new EvaluateRecordVO();
            List<EvaluateRecordVO> teamLists = new ArrayList<>();
            double lastMoney = 0,  nextMoney = 0, monthMoney = 0, sumMoney = 0;
            Integer increaseMoney = 0;
            for (EvaluateRecordVO evaluateRecordVO1:list) {
                if (evaluateRecordVO1.getTeamGroup() != null && evaluateRecordVO1.getTeamGroup().equals(teamGroup.getTeamGroupName())) {
                    teamLists.add(evaluateRecordVO1);
                    lastMoney += evaluateRecordVO1.getLastMoney();
                    increaseMoney += evaluateRecordVO1.getIncreaseMoney();
                    nextMoney += evaluateRecordVO1.getNextMoney();
                    monthMoney += evaluateRecordVO1.getMonthMoney();
                    sumMoney += evaluateRecordVO1.getSumMoney();
                }
            }
            EvaluateRecordTeam recordTeam = new EvaluateRecordTeam();
            subTotal.setLastMoney(lastMoney);
            subTotal.setIncreaseMoney(increaseMoney);
            subTotal.setNextMoney(nextMoney);
            subTotal.setMonthMoney(monthMoney);
            subTotal.setSumMoney(sumMoney);
            recordTeam.setTeamGroupName(teamGroup.getTeamGroupName());
            recordTeam.setDataList(teamLists);
            recordTeam.setTotal(subTotal);
            teamList.add(recordTeam);
        }
        EvaluateRecordDepart depart = new EvaluateRecordDepart();

        depart.setDepartmentName(departmentName);
        depart.setDepartList(teamList);

        return depart;
    }*/


}
